/*
 * 添加调拨记录
 * 参数   交易码：trancode=61113
 * 
 */

package org.ccams.tran;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.ccams.domain.TMaterielStock;
import org.ccams.domain.TpMovbackD;
import org.ccams.domain.TpMovbackH;
import org.ccams.domain.User;
import org.ccams.web.UserSession;
import org.ccams.web.WebBeanFactory;
import org.json.JSONArray;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

public class Tran61113 extends AbstractJsonTran {

	@SuppressWarnings("unchecked")
	public void buildJSONObject(Map model, JSONObject json, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// 获得用户录入信息
		// 从页面上获得信息
		String mov_no = this.getNewMovno();
		Date cw_date = null;
		try {
			cw_date = new SimpleDateFormat("y-M-d").parse(request.getParameter("cw_date"));
			System.out.println("财务日期:" + cw_date);
		} catch (Exception e) {
		}

		int uid = Integer.parseInt(request.getParameter("uid"));
		System.out.println("调拨部门ID:" + uid);

		int buid = Integer.parseInt(request.getParameter("back_uid"));
		System.out.println("接收部门ID:" + buid);

		// 获得制单人
		HttpSession session = request.getSession();
		UserSession userSession = (UserSession) session.getAttribute("userSession");
		User user = userSession.getUser();
//		String pname = user.getUserName();
		System.out.println("制单人:" + user.getUserName());

		TpMovbackH tmh = new TpMovbackH();
		tmh.setMov_no(mov_no);
//		tmh.setPname(pname);
		tmh.setPid(user.getId());
		tmh.setCw_date(cw_date);
//		tmh.setUname(uname);
//		tmh.setBackuname(backuname);
		tmh.setUid(uid);
		tmh.setBack_uid(buid);
		tmh.setOperdate(new Date());

		// 获得详细信息
		String params = request.getParameter("detail");
		JSONArray detailParams = new JSONArray(params);

		HashMap<String, Object> jsonMap = new HashMap<String, Object>();
		String success = "";
		String message = "";
		int k = 0;
		DataSourceTransactionManager txm = (DataSourceTransactionManager) WebBeanFactory.getBean(
				"transactionManager", request);
		DefaultTransactionDefinition def = new DefaultTransactionDefinition();
		def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
		TransactionStatus status = txm.getTransaction(def);
		try {
			k = getCcamsService().getTpmovbackhDao().insertTpmovbackh(tmh);// 添加调拨主表信息

			Long num = getCcamsService().getTpmovbackhDao().getTpmovbackhByMovno(mov_no).getNum();
			for (int i = 0; i < detailParams.length(); i++) {
				org.json.JSONObject detail = detailParams.optJSONObject(i);
				TpMovbackD tmd = new TpMovbackD();
				tmd.setNum(num);
				tmd.setOrd(i);
				tmd.setMaterielName(detail.getString("materielName"));
				tmd.setBatchno(detail.getString("batchno"));
				tmd.setFactcode(detail.getString("factcode"));
				tmd.setSerialNo(detail.getString("serialNo"));
				try {
					tmd.setProd_date(new SimpleDateFormat("y-M-d").parse(detail.getString("prod_date")));
				} catch (Exception e) {
				}
				try {
					tmd.setEnd_date(new SimpleDateFormat("y-M-d").parse(detail.getString("end_date")));
				} catch (Exception e) {
				}
				tmd.setBatchid(detail.getInt("batchid"));
				tmd.setAmount(detail.getLong("amount"));
				tmd.setBack_price(detail.getDouble("back_price"));
				tmd.setCause(detail.getString("cause"));
				tmd.setKind(Short.parseShort(detail.getString("kind")));
				System.out.println("=================================");
				System.out.println("单据ID 	:	" + tmd.getNum());
				System.out.println("序号 	:	" + tmd.getOrd());
				System.out.println("物料名称 	:	" + tmd.getMaterielName());
				System.out.println("批号 	:	" + tmd.getBatchno());
				System.out.println("厂家条码 	:	" + tmd.getFactcode());
				System.out.println("机身码 	:	" + tmd.getSerialNo());
				System.out.println("生产日期 	:	" + tmd.getProd_date());
				System.out.println("有效期 	:	" + tmd.getEnd_date());
				System.out.println("批次 	:	" + tmd.getBatchid());
				System.out.println("调出数量 	:	" + tmd.getAmount());
				System.out.println("调出价格 	:	" + tmd.getBack_price());
				System.out.println("调出原因 	:	" + tmd.getCause());
				System.out.println("单据类型	:	" + tmd.getKind());
				k = getCcamsService().getTpmovbackdDao().insertTpmovbackd(tmd);// 执行添加
				if (k == 1) {
					TMaterielStock tms = new TMaterielStock();
//					tms.setUname(uname);
//					tms.setMaterielName(detail.getString("materielName"));
					tms.setUid(uid);
					tms.setIdt_materiel(detail.getLong("idt_Materiel"));
					int idt = getCcamsService().getTmaterielstockDao().getIdtStock(tms);
					if (idt == 0) {// 库存中没有此物料记录信息
						txm.rollback(status);
						jsonMap.put("success", "false");
						jsonMap.put("message", "部门库存中无此物料<" + tmd.getMaterielName() + ">的相关记录");
						json.putAll(jsonMap);
						return;
					}
					int stockAmount = getCcamsService().getTmaterielstockDao().getStockAmount(tms);// 取得库存数量
					if (stockAmount < tmd.getAmount()) {// 进行数量判断
						txm.rollback(status);
						jsonMap.put("success", "false");
						jsonMap.put("message", "物料<" + tmd.getMaterielName() + ">的库存不足");
						json.putAll(jsonMap);
						return;
					}
				}
			}
		} catch (Exception ex) {
			txm.rollback(status);
			ex.printStackTrace();
		}
		txm.commit(status);

		if (k == 1) {
			success = "true";
			message = "调拨添加成功";
		} else {
			success = "false";
			message = "调拨添加失败";
		}
		jsonMap.put("success", success);
		jsonMap.put("message", message);
		json.putAll(jsonMap);
	}

	private String getNewMovno() {// 获得此调拨单的ID
		Long lastMovno = 0l;
		try {
			lastMovno = Long.parseLong(getCcamsService().getTpmovbackhDao().getLastMovno().substring(2));// 获得最后创建的单的ID
		} catch (Exception e) {
		}
		Long realMovno = Long.parseLong(new SimpleDateFormat("yyyyMMdd").format(new Date())) * 1000;// 当前日期*1000得到中间ID
		if (lastMovno < realMovno)
			realMovno += 1;// 最后ID小于中间ID,说明最后创建的单是昨天或以前的
		else
			realMovno = lastMovno + 1;
		return "MV" + realMovno;
	}
}
